package org.freedoit.server;

import java.util.List;

import org.freedoit.client.TaskService;
import org.freedoit.server.om.User;
import org.freedoit.server.service.ServiceManager;
import org.freedoit.server.util.Utils;
import org.freedoit.shared.data.SharedTask;
import org.freedoit.shared.util.Constants;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class TaskServiceImpl extends RemoteServiceServlet implements
		TaskService {

	public Long addTask(SharedTask task) {
		// TODO Auto-generated method stub
		Long currentUserId = getCurrentUserId();
		if (currentUserId == null)
			return null;
		
		Long timestamp = new Long(System.currentTimeMillis());
		
		if (ServiceManager.addNewTask(Utils.fromSharedData(task), currentUserId, null, null, timestamp)) {
			return timestamp;
		} else {
			return null;
		}
	}

	public Long updateTask(SharedTask task) {
		// TODO Auto-generated method stub
		if (getCurrentUserId() == null)
			return null;
		
		Long timestamp = new Long(System.currentTimeMillis());
		if (ServiceManager.updateTask(Utils.fromSharedData(task), timestamp)) {
			return timestamp;
		} else {
			return null;
		}
	}

	public Long deleteTask(Long taskId) {
		// TODO Auto-generated method stub
		if (getCurrentUserId() == null)
			return null;
		
		Long timestamp = new Long(System.currentTimeMillis());
		if (ServiceManager.deleteTask(taskId, timestamp)) {
			return timestamp;
		} else {
			return null;
		}
	}

	public Long finishTask(Long taskId) {
		// TODO Auto-generated method stub
		if (getCurrentUserId() == null)
			return null;
		
		Long timestamp = new Long(System.currentTimeMillis());
		if (ServiceManager.setTaskFinished(taskId, Boolean.TRUE, timestamp)) {
			return timestamp;
		} else {
			return null;
		}
	}

	public Long unfinishTask(Long taskId) {
		// TODO Auto-generated method stub
		if (getCurrentUserId() == null)
			return null;
		
		Long timestamp = new Long(System.currentTimeMillis());
		if (ServiceManager.setTaskFinished(taskId, Boolean.FALSE, timestamp)) {
			return timestamp;
		} else {
			return null;
		}
	}

	public List<SharedTask> asyncTaskList(Long timestamp) {
		// TODO Auto-generated method stub
		return null;
	}
	
	private Long getCurrentUserId()
	{
		User currentUser = (User)(this.getThreadLocalRequest().getSession().getAttribute(Constants.DOIT_USER_KEY));
		if (currentUser == null) {
			return null;
		} else {
			return currentUser.getUserId();
		}
		
	}
}
